package com.example.javamaday.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;
import java.util.List;

/**
 * 虚引用Demo
 */
public class PhantomReferenceDemo {

    private static final List<Object> LIST = new LinkedList<>();
    private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue<>();

    public static void main(String[] args) {
        final PhantomReference<Object> phantomReference = new PhantomReference<>(new Object(), QUEUE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    LIST.add(new byte[1024 * 1024]);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(phantomReference.get());
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Reference<? extends Object> poll = QUEUE.poll();
                    if (poll != null) {
                         System.out.println("--虚引用对象被回收了--");
                    }
                }
            }
        }).start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
